using System;
using System.Collections.Generic;
using System.IO;

namespace ProjectEuler.Core
{
    public class Problem67 : IProjectEulerProblem
    {
        protected IList<int[]> ListOfRows(string filename)
        {
            var lines = File.ReadLines(filename);
            var list = new List<int[]>();
            foreach (var line in lines)
            {
                list.Add(StringArrayToIntArray(line.Trim().Split(' ')));
            }
            return list;
        }

        private int[] StringArrayToIntArray(string[] strarray)
        {
            var intarray = new int[strarray.Length];
            for (int i = 0; i < strarray.Length; i++)
            {
                intarray[i] = int.Parse(strarray[i]);
            }
            return intarray;
        }

        protected int CalculateMaxPath(IList<int[]> rows)
        {
            for (int i = rows.Count - 2; i >= 0; i--)
            {
                var row = rows[i];
                var underrow = rows[i + 1];
                var calcrow = new int[row.Length];

                for (int j = 0; j < row.Length; j++)
                {
                    int maxval = row[j];
                    if (underrow[j] > underrow[j + 1])
                    {
                        maxval += underrow[j];
                    }
                    else
                    {
                        maxval += underrow[j + 1];
                    }
                    calcrow[j] = maxval;
                }
                calcrow.CopyTo(rows[i], 0);
            }

            return rows[0][0];
        }        

        public int Number
        {
            get { return 67; }
        }

        public string Description
        {
            get { return "Find the maximum total from top to bottom in the given triangle.txt"; }
        }

        public string Answer
        {
            get { return CalculateMaxPath(ListOfRows("GivenFiles\\triangle.txt")).ToString(); }
        }
    }
}